package com.lbagroup.giscovery;

import java.io.File;
import java.text.DecimalFormat;
import java.util.Stack;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.lbagroup.giscovery.R;
import com.lbagroup.giscovery.ShareContent.UploadDataAsyncTask;

/** 
 * Activity for letting a user to manage the settings of the application 
 * 
 * This activity is used to let user manage the different settings of the application. 
 * 
 * @author XH 
 * @version 2011.1105 
 * @since 0.2 
 */
public class Setting extends Activity {

	// Declare our Views, so we can access them later
	/** Called when the activity is first created. */
	   public static final String MO_PROF="ProferenceFile"; // variable for the preference file
	   public static final String SET_NUMBER = "Number";   //variable for keeping the number of results parameter in the preference file
	    public static final String SET_PERIOD = "Period";  // variable for keeping the interest period parameter in the preference file
	    public static final String SET_TAG = "Tag";  // variable for keeping the key words in the preference file
	   
	    /** 
		 * the flag that tells if user has made changes to any settings in the current activity
		 */
	    public int iChangeFlag=0;
	    
	    private Button btnClear; //the clear button object
	    private Button btnSave;  // the Save button object
		private Button btnCancel; // the Cancel button object
		private TextView txtFileSize; // the TextView object that shows the total size of the local Giscovery folder
	    
		/** 
		 * Number of returned results from search
		 */  
	    private String mSet_Number="3";
	    
	    /** 
	     * The time period for taking the results from the search and update. i.e.
	     * the search results should focus on the last 2 days if the value is "2 days" for this variable 
	     */  
	    private String mSet_Period="2 days"; 
	    
	    /** 
	     * The list of key words for the search and update actions. 
	     */  
	    private String mSet_Tag="Copenhagen,Restaurant,Pizza"; 
	    
	    /** 
	     * size of files saved specifically for this application.
	     */  
	    private double mFileSize=0;
      // use Shared Preference to save the values
      // here deploy default values if was null	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        
        
        /**
         * The following lines read the default values to the Number, Period and Tags variables. If there
         * are null, then set a default value for each. 
         * 
         */
        SharedPreferences pref = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
		mSet_Number  = pref.getString(SET_NUMBER, null);
		if(mSet_Number==null)
			mSet_Number="3";
		mSet_Period = pref.getString(SET_PERIOD, null);
		if(mSet_Period==null)
			mSet_Period="2 days";
		mSet_Tag= pref.getString(SET_TAG, null);
		if(mSet_Tag==null)
			mSet_Tag="Copenhagen,Restaurant,Pizza";
		
		
    // create the spinner for number of results
        Spinner spinner = (Spinner) findViewById(R.id.numofresults_spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.numofresults_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        spinner.setAdapter(adapter);
        int i = adapter.getPosition(mSet_Number);
        spinner.setSelection(i);
        
        spinner.setOnItemSelectedListener(new NumOfResultsOnItemSelectedListener());

     // create the spinner for the interest period
        Spinner spinner1 = (Spinner) findViewById(R.id.period_spinner);
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
                this, R.array.period_array, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter1);
        i = adapter1.getPosition(mSet_Period);
        spinner1.setSelection(i);
        spinner1.setOnItemSelectedListener(new PeriodOnItemSelectedListener());
     
       //change the text to show how much historical data has been created
        showFileSize();
        btnClear = (Button)findViewById(R.id.settings_clear);
        btnClear.setOnClickListener(mBTNCLEAR);
        
        TextView txtVW_Tags = (TextView) findViewById(R.id.settings_tags);
        txtVW_Tags.setText(mSet_Tag);
        
      //setting the default value for the tags  
        btnSave=(Button)findViewById(R.id.Settings_btnSave);
        btnSave.setOnClickListener(mBTNSAVE);
        btnCancel = (Button)findViewById(R.id.Settings_btnCancel);
        btnCancel.setOnClickListener(mBTNCANCEL);
       //define the save and cancel button
        
    }
    
    /** 
     * This method shows the size of the files save in the giscovery directory in the sdcard of the phone 
	 *
     */
    private void showFileSize(){
    	   File sdImageMainDirectory = new File("/sdcard/giscovery");
           mFileSize=dirSize(sdImageMainDirectory);
           txtFileSize=(TextView)findViewById(R.id.settings_txthistorydata);
           String msize=String.valueOf(mFileSize);
           txtFileSize.setText("There are "+msize+" KB historical data");
           btnClear = (Button)findViewById(R.id.settings_clear);
           if(mFileSize==0){
        	   btnClear.setEnabled(false);
           }
           else
        	   btnClear.setEnabled(true);
        return;
    }
    
    /** 
     * The inner class that is used when an item is picked on the NumberofResult  list control 
	 *
	 * When an item is picked, the mSet_Number variable changes it value. And the changeFlag variable is notified. 
     */
    public class NumOfResultsOnItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        	String str=parent.getItemAtPosition(pos).toString().trim();
        	if(str!=mSet_Number){
        		mSet_Number=str;
        		iChangeFlag=1;
        	}
        }

        public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }
    
    /** 
     * The inner class that is used when an item is picked on the Period  list control 
     * 
     * When an item is picked the mSet_Period variable change its value. And the changeflag variable is notified.
	 *
     */
    public class PeriodOnItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        	//mSet_Period=parent.getItemAtPosition(pos).toString();
        	String str=parent.getItemAtPosition(pos).toString().trim();
        	if(str!=mSet_Period){
        		mSet_Period=str;
        		iChangeFlag=1;
        	}
        }

        public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }

    /** 
     * The method used to clear the locally saved files
	 *
     */
    public final Button.OnClickListener mBTNCLEAR = new Button.OnClickListener() {
        public void onClick(View v) {
        	if(mFileSize>0){
	        	AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
	            builder.setMessage("This will remove all saved Giscovery files, are you sure to proceed? ")
	                   .setCancelable(false)
	                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	                       public void onClick(DialogInterface dialog, int id) {
	                    	   File sdImageMainDirectory = new File("/sdcard/giscovery");
	                    	   clearAllFiles(sdImageMainDirectory);
	                    	   showFileSize();
	                       }
	                   })
	                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
	                       public void onClick(DialogInterface dialog, int id) {
	                            dialog.cancel();
	                       }
	                   });
	            AlertDialog alert = builder.create();
	            alert.show();
        	}
        }
      };
      
      /** 
       * The method that deletes all files in a directory.
  	   *
       */
    private int clearAllFiles(File dir){
    	    	// Get all files in directory
    	int ires=1;
    	File[] files = dir.listFiles();
    	for (File file : files)
    	{
    	   // Delete each file

    	   if (!file.delete())
    	   {
    	       // Failed to delete file

    	       ires=0;
    	   }
    	}
    	return ires;
    }
    
    /** 
     * The method that saves all current changes to the settings made in the activity 
	 *
     */
      public final Button.OnClickListener mBTNSAVE = new Button.OnClickListener() {
          public void onClick(View v) {
          
        	  
        	  TextView txtVW_Tags = (TextView) findViewById(R.id.settings_tags);
	          String str=txtVW_Tags.getText().toString().trim();
	          if(str!=mSet_Tag){
	        	  mSet_Tag=str;
	        	  iChangeFlag=1;
	          }
	          
        	  if(iChangeFlag==1){
        		getSharedPreferences(MO_PROF,MODE_PRIVATE)
                .edit()
                .putString(SET_NUMBER, mSet_Number)
                .putString(SET_PERIOD, mSet_Period)
                .putString(SET_TAG, mSet_Tag)
                .commit();
                 
        		 AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
                 builder.setMessage("Changes are saved ")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                 Setting.this.finish();
                            }
                        });
                        
                 AlertDialog alert = builder.create();
                 alert.show();
        	  }
        	  else{
        		  Setting.this.finish();
        	  }
          }
        };
        /** 
         * The method that is triggered when the cancel button is clicked. 
    	 *
         */
        public final Button.OnClickListener mBTNCANCEL = new Button.OnClickListener() {
            public void onClick(View v) {
            	Setting.this.finish();
     			
            }
          };
         
          /** 
           * The method that calculates the storage size of all files in a folder. 
      	   *
           */
          private static double dirSize(File dir) {
        	    long result = 0;
        	    
        	    Stack<File> dirlist= new Stack<File>();
        	    dirlist.clear();

        	    dirlist.push(dir);

        	    while(!dirlist.isEmpty())
        	    {
        	        File dirCurrent = dirlist.pop();

        	        File[] fileList = dirCurrent.listFiles();
        	        if(fileList==null)
        	        	break;
        	        for (int i = 0; i < fileList.length; i++) {

        	            if(fileList[i].isDirectory())
        	                dirlist.push(fileList[i]);
        	            else
        	                result += fileList[i].length();
        	        }
        	    }
        	    double a=(double)result;
        	    a=a/1024;
        	    DecimalFormat df = new DecimalFormat("#.##");
        	    String s=df.format(a);
        	    double b=Double.valueOf(s);

        	    return b; //results in k-bytes,rounded to two decimal places
        	}

}